import FormValidate from '@/utils/validate/form';
import schema from '@/uview-ui/libs/util/async-validator';

// 检测
export function checkValue(e, key) {
  this.validation(key);
}

// 校验数据
export function validation(key, callback = () => {}) {
  let self = this;
  //拿到需要校验的数据
  let fieldValue = this.form.data[key];
  //拿到需要检验的规则
  let rules = this.form.rules[key];
  // 判空
  if (!rules || rules.length === 0) {
    return callback('');
  }
  // 设置当前的装填，标识为校验中
  let validateState = 'validating';
  // 调用async-validator的方法
  let validator = new schema({
    [key]: rules
  });
  // 校验
  validator.validate(
    {
      [key]: fieldValue
    },
    {
      firstFields: true
    },
    (errors, fields) => {
      // 记录状态和报错信息
      validateState = !errors ? 'success' : 'error';
      let validateMessage = errors ? errors[0].message : '';
      self.form.error[key] = validateMessage;
      callback(validateMessage);
    }
  );
}

// 校验全部数据
export function validateAll(callback) {
  let self = this;
  return new Promise(resolve => {
    // 对当前所有表单检验
    let valid = true; // 默认通过
    let count = 0; // 用于标记是否检查完毕
    let errorArr = []; // 存放错误信息
    
    let curFormData = self.form.data;
    
    console.log(curFormData)

    Object.keys(curFormData).map(field => {
      self.validation(field, error => {
        // 如果回调有error
        if (error) {
          valid = false;
          errorArr.push(error);
        }
        if (++count === Object.keys(curFormData).length) {
          resolve(valid);
          if (errorArr.length) {
            this.$u.toast(errorArr[0]);
          }
          if (typeof callback == 'function') callback(valid);
        }
      });
    });
  });
}

// 手机号是否输入完毕
export function mobileInput(e, key) {
  this.form.data.isMobileEnd = this.$u.test.mobile(this.form.data.mobile);
  this.validation(key);
}

// 获取短信验证码
export function getSmsCode(type) {
  const self = this;
  if (self.form.data.isMobileEnd && !self.disabledCode) {
    self.$http(
      'common.smsSend',
      {
        mobile: self.form.data.mobile,
        event: type
      },
      '获取验证码中...'
    ).then(res => {
      if (res.code === 1) {
        self.codeChange();
        self.$u.toast('验证码已发送，请注意查收短信');
      } else {
        self.$u.toast(res.msg);
      }
    });
  } else {
    self.$u.toast('请稍后再试');
  }
}

// 倒计时
export function codeChange() {
  if (this.disabledCode) return;
  this.disabledCode = true;
  let n = 10;
  this.codeText = n + 's';
  const run = setInterval(() => {
    n -= 1;
    if (n < 0) {
      clearInterval(run);
    }
    this.codeText = n + 's';
    if (this.codeText < 0 + 's') {
      this.disabledCode = false;
      this.codeText = '重新获取';
    }
  }, 1000);
}

// 规则校验
export function validateSubmit() {
  if (['accountLogin', 'smsLogin', 'register'].includes(this.authType) && !this.protocol) {
    this.$u.toast('请同意用户协议');
    return false;
  }
  
  return this.validateAll();
}
